package cn.sdormitory.exam.service.impl;

import cn.sdormitory.basedata.dao.BCourseDao;
import cn.sdormitory.common.api.CommonPage;
import cn.sdormitory.common.utils.SysUserUtils;
import cn.sdormitory.exam.dao.*;
import cn.sdormitory.exam.entity.*;
import cn.sdormitory.exam.service.ExamService;
import cn.sdormitory.exam.vo.*;
import cn.sdormitory.sys.dao.SysDictDetailDao;
import cn.sdormitory.sys.entity.SysDictDetail;
import cn.sdormitory.sys.entity.SysUser;
import cn.sdormitory.sys.enums.StatusEnums;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author : yy
 * @date: 2024/12/28 9:22
 * @description:
 */
@Service
public class ExamServiceImpl extends ServiceImpl<ExamDao, Exam> implements ExamService {
    @Resource
    private ExamDao examDao;
    @Resource
    private ExamClassDao examClassDao;
    @Resource
    private ExamCourseDao examCourseDao;
    @Resource
    private ExamCourseStudentScoreDao examCourseStudentScoreDao;


    @Resource
    private BCourseDao bCourseDao;
    @Resource
    private SysDictDetailDao sysDictDetailDao;


    @Override
    public CommonPage<Exam> getList(String examName, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Exam> list = examDao.getList(examName);
        return CommonPage.restPage(list);
    }
    @Override
    public void delExam(Integer[] ids) {
        List<Integer> idList = Arrays.asList(ids);
        examDao.deleteBatchIds(idList);
    }
    @Override
    public void updateExamRelease(Integer examId, Boolean isRelease) {
        LambdaUpdateWrapper<Exam> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Exam::getId, examId).set(Exam::getIsRelease, isRelease);
        examDao.update(null, wrapper);
    }

    @Override
    public EditExamVo getEditExam(Integer id) {
        EditExamVo editExamVo = new EditExamVo();

        List<EditExamVo> editExamVos = examDao.getEditExam(id);
        if(!editExamVos.isEmpty()) {
            EditExamVo baseVo = editExamVos.get(0);
            editExamVo.setId(baseVo.getId());
            editExamVo.setName(baseVo.getName());
            editExamVo.setExamDate(baseVo.getExamDate());
            editExamVo.setRemark(baseVo.getRemark());

            Set<Integer> classIds = new HashSet<>();
            Set<List<Object>> courseOpt = new HashSet<>();
            for(EditExamVo examVo : editExamVos) {
                // 添加班级id到集合中
                classIds.add(examVo.getClassId());

                // 创建包含专业id, 课程id, 考试类型的列表，并添加到集合中
                List<Object> courseList = Arrays.asList(examVo.getSubjectId(), examVo.getCourseId(), examVo.getExamType());
                courseOpt.add(courseList);
            }
            editExamVo.setClassIds(classIds);
            editExamVo.setCourseOpt(courseOpt);
        }

        return editExamVo;
    }
    @Override
    @Transactional
    public void editExam(EditExamVo editExamVo) {
        SysUser user = SysUserUtils.getSysUser(); //获取当前登录用户信息
        if (user == null) {
            throw new RuntimeException("当前用户未登录");
        }

        Exam exam = new Exam();
        exam.setName(editExamVo.getName());
        exam.setExamDate(editExamVo.getExamDate());
        exam.setRemark(editExamVo.getRemark());
        exam.setModifyBy(user.getUsername());
        if(editExamVo.getId()!=null) {
            exam.setId(editExamVo.getId());
            examDao.updateById(exam);
        }else {
            //新增考试
            exam.setCreateBy(user.getUsername());
            examDao.insert(exam);

            //新增考试班级
            Set<Integer> classIds = editExamVo.getClassIds();
            classIds.forEach(classId -> {
                ExamClass examClass = new ExamClass();
                examClass.setExamId(exam.getId());
                examClass.setClassId(classId);
                examClassDao.insert(examClass);
            });

            //新增考试课程
            Set<List<Object>> courseOpt = editExamVo.getCourseOpt();
            courseOpt.forEach(obj -> {
                ExamCourse examCourse = new ExamCourse();
                examCourse.setExamId(exam.getId());
                examCourse.setCourseId((Integer) obj.get(1));
                examCourse.setExamType(obj.get(2).toString());
                examCourseDao.insert(examCourse);
            });
        }
    }
    @Override
    public List<ExamClassVo> getExamClassList(Integer examId) {
        return examDao.getExamClassList(examId);
    }
    @Override
    public List<Map<String, Object>> getCourseExamTypeOption() {
        List<Map<String,Object>> resultList = new ArrayList<>();
        //获取所有专业课程
        List<Map<String, Object>> subjectCourse = bCourseDao.getSubjectCourse();
        //获取所有考试类型
        List<SysDictDetail> examType = sysDictDetailDao.selectList(new LambdaQueryWrapper<SysDictDetail>()
                .eq(SysDictDetail::getDictType, "exam_type")
                .eq(SysDictDetail::getStatus, StatusEnums.ENABLE.getKey()));
        List<Map<String,Object>> dictList = new ArrayList<>();
        for(SysDictDetail detail: examType) {
            HashMap<String, Object> dictMap = new HashMap<>();
            dictMap.put("value",detail.getDictValue());
            dictMap.put("label",detail.getDictLabel());
            dictList.add(dictMap);
        }

        Map<Long, Map<String, Object>> subjectMap = new HashMap<>();
        for (Map<String, Object> map : subjectCourse) {
            long subjectId = (long) map.get("subjectId");
            long courseId = (long) map.get("courseId");
            String subjectName = (String) map.get("subjectName");
            String courseName = (String) map.get("courseName");

            // 检查 subjectMap 中是否已经有 subjectId 的记录
            if (!subjectMap.containsKey(subjectId)) {
                Map<String, Object> subjectEntry = new HashMap<>();
                subjectEntry.put("value", subjectId);
                subjectEntry.put("label", subjectName);
                subjectEntry.put("children", new ArrayList<>());
                subjectMap.put(subjectId, subjectEntry);
                resultList.add(subjectEntry);
            }

            Map<String, Object> subjectEntry = subjectMap.get(subjectId);
            List<Map<String, Object>> subjectChildren = (List<Map<String, Object>>) subjectEntry.get("children");

            // 检查 subjectChildren 中是否已经有 courseId 的记录
            boolean courseFound = false;
            for (Map<String, Object> child : subjectChildren) {
                if ((long) child.get("value") == courseId) {
                    courseFound = true;
                    break;
                }
            }
            if (!courseFound) {
                Map<String, Object> courseEntry = new HashMap<>();
                courseEntry.put("value", courseId);
                courseEntry.put("label", courseName);
                courseEntry.put("children", dictList);
                subjectChildren.add(courseEntry);
            }
        }
        return resultList;
    }

    @Override
    public List<ExamCourseTabVo> getExamCourseTab(Integer examId,String courseType) {
        return examDao.getExamCourseTab(examId,courseType);
    }
    @Override
    public void editExamCourse(List<ExamCourse> examCourses) {
        for (ExamCourse examCourse : examCourses) {
            if(examCourse.getId() != null) {
                examCourseDao.updateById(examCourse);
            }
        }
    }
    @Override
    public List<ExamCourseScoreVo> getExamCourseScore(Integer classId, Integer examId, Integer courseId,String studentName,String examType) {
        return examDao.getExamCourseScore(classId,examId,courseId,studentName,examType);
    }
    @Override
    @Transactional
    public void enterExamCourseStudentScore(List<ExamCourseScoreVo> examCourseScoreVos) {
        SysUser user = SysUserUtils.getSysUser(); //获取当前登录用户信息
        if (user == null) {
            throw new RuntimeException("当前用户未登录");
        }

        for(ExamCourseScoreVo scoreVo : examCourseScoreVos) {
            ExamCourseStudentScore score = new ExamCourseStudentScore();
            BeanUtils.copyProperties(scoreVo,score);
            score.setModifyBy(user.getUsername());
            if(scoreVo.getExamCourseStudentScoreId() != null) { //修改
                score.setId(scoreVo.getExamCourseStudentScoreId());
                examCourseStudentScoreDao.updateById(score);
            }else { //新增
                score.setCreateBy(user.getUsername());
                examCourseStudentScoreDao.insert(score);
            }
        }
    }
    @Override
    public List<ExamTotalScoreVo> getExamTotalScore(Integer classId, Integer examId,String studentName) {
        return examDao.getExamTotalScore(classId,examId,studentName);
    }

}
